import { Request, Response } from 'express';
import { asyncHandler, ApiError } from '../middlewares/errorHandler';
import { hashPassword, comparePassword } from '../utils/bcrypt';
import { generateToken } from '../utils/jwt';
import prisma from '../config/database';

// 用户注册
export const register = asyncHandler(async (req: Request, res: Response) => {
  const { email, username, password } = req.body;

  // 检查用户是否已存在
  const existingUser = await prisma.user.findFirst({
    where: {
      OR: [{ email }, { username }],
    },
  });

  if (existingUser) {
    throw new ApiError(400, 'Email or username already exists');
  }

  // 加密密码
  const hashedPassword = await hashPassword(password);

  // 创建用户
  const user = await prisma.user.create({
    data: {
      email,
      username,
      password: hashedPassword,
      role: 'STUDENT',
    },
  });

  // 创建用户资料
  await prisma.userProfile.create({
    data: {
      userId: user.id,
    },
  });

  // 生成token
  const token = generateToken({
    userId: user.id,
    email: user.email,
    role: user.role,
  });

  res.status(201).json({
    code: 201,
    message: 'User registered successfully',
    data: {
      user: {
        id: user.id,
        email: user.email,
        username: user.username,
        role: user.role,
      },
      token,
    },
  });
});

// 用户登录
export const login = asyncHandler(async (req: Request, res: Response) => {
  const { email, password } = req.body;

  // 查找用户
  const user = await prisma.user.findUnique({
    where: { email },
  });

  if (!user) {
    throw new ApiError(401, 'Invalid email or password');
  }

  // 验证密码
  const isPasswordValid = await comparePassword(password, user.password);
  if (!isPasswordValid) {
    throw new ApiError(401, 'Invalid email or password');
  }

  // 生成token
  const token = generateToken({
    userId: user.id,
    email: user.email,
    role: user.role,
  });

  res.json({
    code: 200,
    message: 'Login successful',
    data: {
      user: {
        id: user.id,
        email: user.email,
        username: user.username,
        role: user.role,
        avatar: user.avatar,
      },
      token,
    },
  });
});

// 获取当前用户信息
export const getCurrentUser = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user!.userId;

  const user = await prisma.user.findUnique({
    where: { id: userId },
    include: {
      profile: true,
    },
  });

  if (!user) {
    throw new ApiError(404, 'User not found');
  }

  res.json({
    code: 200,
    message: 'Success',
    data: {
      id: user.id,
      email: user.email,
      username: user.username,
      role: user.role,
      avatar: user.avatar,
      profile: user.profile,
    },
  });
});

// 验证邮箱
export const verifyEmail = asyncHandler(async (req: Request, res: Response) => {
  const { token } = req.params;

  // 这里应该从Redis或数据库验证token
  // 简化实现,实际应该存储验证token
  console.log('Email verification token:', token);

  res.json({
    code: 200,
    message: 'Email verified successfully',
    data: null,
  });
});
